﻿using System;
using System.Collections;
using System.Text;
using System.Text.Json;
using StackExchange.Redis;

namespace xBei.Redis.Extension {
    /// <summary>
    /// 快捷操作
    /// </summary>
    public static class Helper {
        internal static string JoinString(this IEnumerable list, char separator) => JoinString(list, $"{separator}");
        internal static string JoinString(this IEnumerable list, string separator) {
            if (list == null) return string.Empty;
            var sb = new StringBuilder();
            var first = true;
            foreach (var item in list) {
                if (first) {
                    sb.Append(item.ToString());
                    first = false;
                } else {
                    sb.AppendFormat("{0}{1}", separator, item);
                }
            }
            return sb.ToString();
        }

        internal static string Serialize(this object? obj)
            => JsonSerializer.Serialize(obj, RedisClient.JsonSerializerOptions);
        internal static T? Deserialize<T>(this string? json)
            => string.IsNullOrWhiteSpace(json)
                ? default
                : JsonSerializer.Deserialize<T>(json, RedisClient.JsonSerializerOptions);

        /// <summary>
        /// 读取消息
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="channelMessage"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T? GetMessage<T>(this ChannelMessage channelMessage, T? defaultValue = default) where T : class, new()
            => channelMessage.Message.IsNullOrEmpty ? defaultValue : channelMessage.Message.ToString().Deserialize<T>() ?? defaultValue;
        /// <summary>
        /// 读取消息
        /// </summary>
        /// <param name="channelMessage"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static DateTime GetDateTimeMessage(this ChannelMessage channelMessage, DateTime defaultValue = default)
            => channelMessage.Message.IsNullOrEmpty ? defaultValue : new DateTime((long)channelMessage.Message);
    }
}
